package cn.akwangl.socket.simple;

import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Socket 简单client测试.
 * <p>
 * 当用户一直输入时,会将数据发给服务端,如果用户输入{@link SimpleService#QUIT}关键字则关闭socket连接.
 *
 * @author 阿坤同学
 * @date 2022/6/18 15:26
 * @since 0.0.6
 */
@Slf4j
public class SimpleClient {

    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(SimpleService.SERVER_ADDRESS, SimpleService.SERVER_PORT);
        Socket socket = new Socket();
        try {
            socket.connect(inetSocketAddress);
            log.info("如需停止程序请输入:quit 关键字并回车");
            Scanner sc = new Scanner(System.in);

            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());

            while (sc.hasNext()) {
                String userMsg = sc.nextLine();
                // 客户端发送消息给服务端
                out.writeUTF(userMsg);

                log.info("userMsg:{}", userMsg);
                // 客户端接收服务端消息.
                if (!SimpleService.QUIT.equals(userMsg)) {
                    log.info("来自服务端的消息:{}", in.readUTF());
                } else {
                    socket.close();
                    sc.close();
                    log.info("客户端socket 已断开连接.");
                    break;
                }
            }
        } catch (IOException e) {
            log.error("Socket 连接错误", e);
        } finally {
            if (!socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("client socket 关闭失败", e);
                }
            }
        }
    }
}
